import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/C.dart';
import 'package:huajianshe_app/common/TS.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/space.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';
import 'model/CircleModel.dart';

//关联圈子
// ignore: must_be_immutable
class LinkCirclesPage extends StatefulWidget {

  List<SelectedCircle>? selected;
  final List<SimpleCircleInfo>? joined;
  final List<SimpleCircleInfo>? created;

  LinkCirclesPage(this.joined, this.created, this.selected, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LinkCirclesPageState();
  }
}

class _LinkCirclesPageState extends BaseState<LinkCirclesPage> {

  @override
  Widget build(BuildContext context) {
    print('selected size: ${widget.selected?.length}');
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CAppBar(bgColor: Colors.white, title: '关联圈子',),
      body: SimpleScrollView(children: [
        H(10),
        Row(children: [
          VD(18.0, width: 3, color: C.primary,),
          W(13),
          Text('已选圈子', style: TS(15, C.gray333)),
          W(4),
          Text('最多可选3个，我创建的圈子可"推荐"到首页', style: TS(12, C.gray999))
        ]),
        H(12),
        buildSelectedCircles(),
        H(16),
        D(),
        H(13),
        Row(children: [
          VD(18.0, width: 3, color: C.primary,),
          W(13),
          Text('我加入的', style: TS(15, C.gray333)),
        ]),
        H(12),
        buildJoinedCircles(),
        H(16),
        D(),
        H(13),
        Row(children: [
          VD(18.0, width: 3, color: C.primary,),
          W(13),
          Text('我创建的', style: TS(15, C.gray333)),
        ]),
        H(13),
        buildCreatedCircles(),
        H(12)
      ],
      bottomView: SmartButton(text: '确认', fontSize: 17, textColor: Colors.white, height: 50, width: double.infinity,
          onPressed: () { AppNavigator.pop(context, widget.selected); })),
    );
  }

  Widget buildSelectedCircles() {
    if (widget.selected?.isNotEmpty == true) {
      return Padding(padding: EdgeInsets.symmetric(horizontal: 16),
        child: RoundedCornerWidget(child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
          ...widget.selected!.map((e) {
            List<Widget> widgets = [];
            widgets.add(Text('#${e.circle.title}', style: TS(14, e.isRecommended ? C.primary : C.gray666)));
            if (e.isCreated) {
              widgets.add(Spacer());
              widgets.add(GestureDetector(onTap: () { recommend(e); }, child: LoadImage('ic_recommendation')));
              widgets.add(W(2));
              if (e.isRecommended) {
                widgets.add(GestureDetector(onTap: () { recommend(e); }, child: Text('已推荐', style: TS(13, C.primary))));
              } else {
                widgets.add(GestureDetector(onTap: () { recommend(e); }, child: Text('推首页', style: TS(13, C.gray333))));
              }
            }
            return Padding(padding: EdgeInsets.symmetric(horizontal: 13, vertical: 6), child: Row(children: widgets));
          }).toList()
        ]), borderWidth: 0, radius: 13, backgroundColor: C.grayF6)
      );
    }
    return H(0);
  }

  Widget buildJoinedCircles() {
    if (widget.joined?.isNotEmpty == true) {
      return Padding(padding: EdgeInsets.symmetric(horizontal: 13),
          child: Wrap(spacing: 10, runSpacing: 10, children: [
            ...widget.joined!.map((e) {
              return GestureDetector(onTap: () { select(e, false); },
                  child: RoundedCornerWidget(child: Text('#${e.title}', style: TS(14, C.gray0D0E15)), height: 32, radius: 16, borderWidth: 0,
                      backgroundColor: isSelected(e) ? C.primary : C.grayF6, padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6)));
            })
          ])
      );
    }
    return H(0);
  }

  Widget buildCreatedCircles() {
    if (widget.created?.isNotEmpty == true) {
      return Padding(padding: EdgeInsets.symmetric(horizontal: 13),
          child: Wrap(spacing: 10, runSpacing: 10, children: [
            ...widget.created!.map((e) {
              return GestureDetector(onTap: () { select(e, true); },
                  child: RoundedCornerWidget(child: Text('#${e.title}', style: TS(14, C.gray0D0E15),), height: 32, radius: 16, borderWidth: 0,
                      backgroundColor: isSelected(e) ? C.primary : C.grayF6, padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6)));
            })
          ])
      );
    }
    return H(0);
  }

  bool isSelected(SimpleCircleInfo info) {

    if (widget.selected == null) return false;
    for (SelectedCircle info_ in widget.selected!) {
      // print('is selected: ${info.id} ${info_.circle.id}');
      if (info.id == info_.circle.id) return true;
    }
    return false;
  }

  recommend(SelectedCircle selectedCircle) {
    selectedCircle.isRecommended = !selectedCircle.isRecommended;
    setState(() => {});
  }

  select(SimpleCircleInfo circle, bool isCreated) {
    if (widget.selected == null) widget.selected = [];
    for (int i = 0; i < widget.selected!.length; i++) {
      if (widget.selected![i].circle.id == circle.id) {
        widget.selected!.removeAt(i);
        setState(() => {});
        return;
      }
    }
    if (isCreated) {
      for (int i = 0; i < widget.selected!.length; i++) {
        if (widget.selected![i].isCreated) {
          Toast.show('最多只能选择1个我所创建的圈子');
          return;
        }
      }
    }
    if (widget.selected!.length < 3) {
      SelectedCircle selectedCircle = SelectedCircle(circle, isCreated);
      widget.selected!.add(selectedCircle);
      setState(() => {});
    }
  }
}

class SelectedCircle { //已选圈子的模型
  final SimpleCircleInfo circle;
  final bool isCreated;
  bool isRecommended = false;

  SelectedCircle(this.circle, this.isCreated);

}